<route lang="yaml">
meta:
  title: 内容处理
</route>

<script setup lang="ts">
import { ElNotification } from 'element-plus'
import { chat } from '@/utils/openapi'
import {useXueBengStore} from "@/store/modules/xuebeng.ts";
import VoicePage from "@/components/VoicePage.vue";

const promptStore = usePromptStore()
const xueBengStore = useXueBengStore()

const bookNameModel = ref({
  sourceName: '',
  targetName: '请先推导书名',
  targetList: ['请先推导书名'],
  reference: '',
  loading: false,
  dialog: false,
  dialogLoading: false,
})

const roleNameModel = ref({
  sourceRoleName: '',
  targetRoleName: '',
  isChange: false,
  loading: false,
  loading2: false,
  dialog: false,
})

const bookContentModel = ref({
  sourceContent: '',
  isChange: false,
})

const novelHeadModel = ref({
  drawer: false,
  sourceNovelHead: '',
  targetNovelHead: '',
  loading: false,
})

const voiceDialog = ref(false)

const roleNameTableData = ref<Array<{
  sourceName: string
  targetName: string
}>>([])

function bookNameChange(msg: string) {
  if (msg.length < 1) {
    ElNotification({
      title: '提示',
      message: '请先填写书名',
      type: 'warning',
    })
  }
  else {
    bookNameModel.value.loading = true
    chat(promptStore.bookNamePrompt, `小说书名: ${msg}`).then((response) => {
      if (response) {
        console.log(response)
        bookNameModel.value.targetList = response.split(',')
        bookNameModel.value.targetName = bookNameModel.value.targetList[0]
      }
      bookNameModel.value.loading = false
      ElNotification({
        title: '推导成功',
        message: '书名推导成功...',
        type: 'success',
      })
    })
  }
}

function selectRoleName(content: string) {
  if (bookContentModel.value.sourceContent.length < 1) {
    ElNotification({
      title: '提示',
      message: '请先粘贴小说原文，在点击角色推导',
      type: 'warning',
    })
  }
  else {
    roleNameModel.value.loading = true
    chat(promptStore.roleNamePrompt, `文章内容: ${content}`).then((response) => {
      if (response) {
        console.log(response)
        roleNameModel.value.sourceRoleName = response
        // 将人名转换为表格数据
        const names = response.split(',')
        roleNameTableData.value = names.map(name => ({
          sourceName: name,
          targetName: name // 默认值与原名相同
        }))

        roleNameModel.value.loading = false
        roleNameModel.value.dialog = true
        ElNotification({
          title: '分析成功',
          message: '人名分析成功...',
          type: 'success',
        })
      }
    })
  }
}

function changeRoleName() {
  if (roleNameModel.value.sourceRoleName.length < 1) {
    ElNotification({
      title: '提示',
      message: '请先进行角色推导',
      type: 'warning',
    })
  }
  else {
    roleNameModel.value.loading2 = true

    // 将当前表格中的原名称组合成请求参数
    const names = roleNameTableData.value.map(item => item.sourceName).join(',')

    chat(promptStore.changeNamePrompt, `请帮我生成名字: ${names}`).then((response) => {
      if (response) {
        console.log(response)
        roleNameModel.value.targetRoleName = response
        // 更新表格中的目标名称
        const newNames = response.split(',')
        roleNameTableData.value.forEach((item, index) => {
          if (index < newNames.length) {
            item.targetName = newNames[index]
          }
        })
      }
      roleNameModel.value.loading2 = false
      ElNotification({
        title: '操作成功',
        message: '新人名生成成功...',
        type: 'success',
      })
    })
  }
}

function generateContentHead(content: string) {
  if (bookContentModel.value.sourceContent.length < 1) {
    ElNotification({
      title: '提示',
      message: '请先粘贴小说原文',
      type: 'warning',
    })
  }
  else {
    novelHeadModel.value.loading = true
    chat(promptStore.novelHeadPrompt, `小说内容: ${content}`).then((response) => {
      if (response) {
        console.log(response)
        novelHeadModel.value.targetNovelHead = response
      }
      novelHeadModel.value.loading = false
      ElNotification({
        title: '操作成功',
        message: '爆款开头生成成功...',
        type: 'success',
      })
    })
  }
}

// 获取字符串前50行的方法
function getFirst50Lines(str: string) {
  // 使用正则表达式分割字符串，兼容不同换行符（\n, \r\n, \r）
  const lines = str.split(/\r\n|\n|\r/);
  // 截取前50行
  const first50 = lines.slice(0, 50);
  // 重新组合为字符串（使用\n作为统一换行符）
  novelHeadModel.value.sourceNovelHead = first50.join('\n');
}

// 获取字符串前50行的方法
function insertNovelContent(content: string) {
  bookContentModel.value.sourceContent = content + bookContentModel.value.sourceContent
  contentOptimization(bookContentModel.value.sourceContent)
  novelHeadModel.value.drawer = false
}

function doChangeRoleName() {
  if (roleNameTableData.value.length < 1) {
    ElNotification({
      title: '提示',
      message: '请先进行新人名生成',
      type: 'warning',
    })
  }
  else {
    let newContent = bookContentModel.value.sourceContent

    // 根据表格数据进行替换
    roleNameTableData.value.forEach(item => {
      newContent = newContent.replaceAll(item.sourceName, item.targetName)
    })

    bookContentModel.value.sourceContent = newContent
    roleNameModel.value.dialog = false
    roleNameModel.value.isChange = true
    ElNotification({
      title: '操作成功',
      message: '一键替换成功...',
      type: 'success',
    })
  }
}

function contentOptimization(content: string) {
  if (content.length < 1) {
    ElNotification({
      title: '提示',
      message: '请先粘贴小说原文，在点击优化',
      type: 'warning',
    })
  }
  else {
    // 1.替换标点符号
    content = content.replaceAll('……', '。')
      .replaceAll(/[；—…、～~]+/g, '，')
      .replaceAll(/["`·《》『』［\]（）【】」「#“”]+/g, '')
      .replaceAll(/[？！。，：；]+/g, '\n')
    // 2.删除空白行
    bookContentModel.value.sourceContent = content.split(/\r?\n/)
      .filter((line) => {
        const trimmed = line.trim()
        // 保留非空行且不是纯数字的行
        return trimmed !== '' && !/^\d+$/.test(trimmed)
      })
      .join('\n')
  }
}

function clear() {
  bookNameModel.value = {
    sourceName: '',
    targetName: '请先推导书名',
    targetList: ['请先推导书名'],
    reference: '',
    loading: false,
    dialog: false,
    dialogLoading: false
  }

  roleNameModel.value = {
    sourceRoleName: '',
    targetRoleName: '',
    isChange: false,
    loading: false,
    loading2: false,
    dialog: false,
  }

  bookContentModel.value = {
    sourceContent: '',
    isChange: false
  }

  novelHeadModel.value = {
    drawer: false,
    sourceNovelHead: '',
    targetNovelHead: '',
    loading: false,
  }

  ElNotification({
    title: '操作成功',
    message: '清空成功',
    type: 'success',
  })
}

function addKeywords() {
  const keywords = [{
    keyword: bookNameModel.value.targetName,
    url: bookNameModel.value.reference.trim()
  }]
  bookNameModel.value.dialogLoading = true
  xueBengStore.addKeywords({
    missionId: 16, // 知乎会员
    keywords: JSON.stringify(keywords),
    from: null
  }).then((response) => {
    if (response) {
      // 登录失效，重新登录
      if (response.data.code === 401) {
        const xueBengConfig = localStorage.xueBengConfig
        if (xueBengConfig) {
          const xbConfig = JSON.parse(xueBengConfig)
          xueBengStore.login({
            type: 1,
            phone: xbConfig.phone,
            password: xbConfig.password,
          }).then(() => {
            // 重新请求接口
            xueBengStore.addKeywords({
              missionId: 16, // 知乎会员
              keywords: JSON.stringify(keywords),
              from: null
            }).then((response) => {
              ElNotification({
                title: '提示',
                message: response.data.info,
                type: 'success',
              })
            })
          })
        }
      }
      else {
        ElNotification({
          title: '提示',
          message: response.data.info,
          type: 'success',
        })
      }
    }
    bookNameModel.value.dialogLoading = false
    bookNameModel.value.dialog = false
  })
}

// 如果是路由过来的
onMounted(() => {
  const rt = useRoute();
  const novelId = rt.query.novelId
  if (novelId && typeof novelId == 'string') {
    xueBengStore.getArticleById(Number.parseInt(novelId)).then((response) => {
      if (response) {
        // 1.赋值小说书名和推广链接
        bookNameModel.value.sourceName = response.data.data.name
        bookNameModel.value.reference = response.data.data.reference
        // 2.赋值小说内容
        const html = response.data.data.content
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = html;
        let result = '';
        const paragraphs = tempDiv.querySelectorAll('p');
        console.log(paragraphs);
        // 提取文本内容并用换行符连接
        paragraphs.forEach(p => {
          result += p.textContent + '\n';
        });
        bookContentModel.value.sourceContent = result;
      }
    })
  }
})

</script>

<template>
  <div>
    <FaPageMain>
      <el-form v-loading="bookNameModel.loading" element-loading-text="书名推导中..." :inline="true" :model="bookNameModel">
        <el-form-item label="小说书名">
          <el-input v-model="bookNameModel.sourceName" style="width: 250px" placeholder="请输入小说原书名..." clearable />
        </el-form-item>
        <el-form-item label="推导结果">
          <el-select
            v-model="bookNameModel.targetName"
            allow-create
            filterable
            style="width: 200px"
            placeholder="推导结果..."
          >
            <el-option
              v-for="item in bookNameModel.targetList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
          <span v-show="bookNameModel.targetList.length > 1" class="i-streamline-stickies-color:validation-1-duo" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="bookNameChange(bookNameModel.sourceName)">
            推导书名
          </el-button>
          <el-button type="primary" @click="bookNameModel.dialog = true">
            提交关键词
          </el-button>
        </el-form-item>
      </el-form>
    </FaPageMain>
    <FaPageMain>
      <el-input v-model="bookContentModel.sourceContent" size="large" placeholder="请粘贴小说原文..." :rows="20" type="textarea" />
    </FaPageMain>
    <FaPageMain>
      <div v-loading="roleNameModel.loading" element-loading-text="角色名字分析中...">
        <el-button type="primary" size="large" @click="selectRoleName(bookContentModel.sourceContent)">
          <span v-show="roleNameModel.isChange"  class="i-streamline-stickies-color:validation-1-duo" />
          角色名字处理
        </el-button>

        <el-button type="primary" size="large" @click="novelHeadModel.drawer = true">
          <span v-show="roleNameModel.isChange"  class="i-streamline-stickies-color:validation-1-duo" />
          文本处理
        </el-button>
        <el-button type="primary" size="large" @click="voiceDialog = true">
          配音生成
        </el-button>
        <el-button type="danger" size="large" @click="clear">
          清空内容
        </el-button>
      </div>
    </FaPageMain>

    <!--  -->
    <el-drawer v-model="novelHeadModel.drawer" :direction="'rtl'" >
      <template #header>
        <h4>爆款开头生成</h4>
      </template>
      <template #default>
        <el-form :model="novelHeadModel" v-loading="novelHeadModel.loading" element-loading-text="爆款开头生成中..." >
          <el-form-item label="小说原文">
            <el-input v-model="novelHeadModel.sourceNovelHead" size="large" placeholder="请粘贴小说原文..." :rows="10" type="textarea" disabled />
          </el-form-item>
          <el-form-item label="爆款开头">
            <el-input v-model="novelHeadModel.targetNovelHead" size="large" placeholder="请粘贴小说原文..." :rows="10" type="textarea" />
            <span v-show="novelHeadModel.targetNovelHead.length > 1" class="i-streamline-stickies-color:validation-1-duo" />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="info" @click="getFirst50Lines(bookContentModel.sourceContent)">读取原文开头</el-button>
          <el-button type="primary" @click="generateContentHead(novelHeadModel.sourceNovelHead)">生成爆款开头</el-button>
          <el-button type="success" @click="insertNovelContent(novelHeadModel.targetNovelHead)">一键优化导入</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 人名替换 -->
    <el-dialog v-model="roleNameModel.dialog" title="人名处理" width="50%">
      <!-- 添加人名表格 -->
      <el-table
        v-loading="roleNameModel.loading2"
        element-loading-text="正在生成新角色名..."
        v-if="roleNameTableData.length > 0"
        :data="roleNameTableData"
        border
      >
        <el-table-column prop="sourceName" label="原文人名" >
          <template #default="scope">
            <el-input v-model="scope.row.sourceName" disabled />
          </template>
        </el-table-column>
        <el-table-column prop="targetName" label="替换人名" >
          <template #default="scope">
            <el-input v-model="scope.row.targetName" placeholder="请输入替换人名" />
          </template>
        </el-table-column>
      </el-table>
      <br>
      <div v-show="!roleNameModel.loading2">
        <el-button type="primary" @click="changeRoleName">
          随机人名
        </el-button>
        <el-button type="primary" @click="doChangeRoleName">
          一键替换
        </el-button>
      </div>
    </el-dialog>

    <el-dialog v-model="bookNameModel.dialog" title="提交关键词" width="500">
      <el-form :model="bookNameModel" v-loading="bookNameModel.dialogLoading">
        <el-form-item label="推广链接">
          <el-input type="textarea" :rows="5" v-model="bookNameModel.reference" placeholder="提示：如果不知道推广链接，可以从新文列表功能点击处理进入本页面..." />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="bookNameModel.dialog = false">取消</el-button>
          <el-button type="primary" @click="addKeywords">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 配音生成模块 -->
    <el-dialog v-model="voiceDialog" title="配音生成" width="80%">
      <VoicePage v-if="voiceDialog" :content="bookContentModel.sourceContent"/>
    </el-dialog>
  </div>
</template>
